package com.example.xupdateLearningProject.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.xupdateLearningProject.R;
import com.example.xupdateLearningProject.custom.CustomUpdateParser;
import com.example.xupdateLearningProject.custom.CustomUpdatePrompt;
import com.example.xupdateLearningProject.http.XHttpUpdateHttpService;
import com.xuexiang.constant.PermissionConstants;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageContainerListFragment;
import com.xuexiang.xpage.base.XPageSimpleListFragment;
import com.xuexiang.xpage.utils.TitleBar;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateChecker;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateParser;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.FileUtils;
import com.xuexiang.xutil.app.IntentUtils;
import com.xuexiang.xutil.app.PathUtils;
import com.xuexiang.xutil.common.ClickUtils;
import com.xuexiang.xutil.display.CProgressDialogUtils;
import com.xuexiang.xutil.display.HProgressDialogUtils;
import com.xuexiang.xutil.resource.ResUtils;
import com.xuexiang.xutil.resource.ResourceUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.io.File;
import java.util.List;
import java.util.Locale;

@Page(name = "XUpdate版本更新")
public class MainFragment extends XPageSimpleListFragment {
    private String mUpdateUrl = "https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_test.json";

    private String mUpdateUrl2 = "https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_forced.json";

    private String mUpdateUrl3 = "https://gitee.com/xuexiangjys/XUpdate/raw/master/jsonapi/update_custom.json";

    private String mDownloadUrl = "https://xuexiangjys.oss-cn-shanghai.aliyuncs.com/apk/xupdate_demo_1.0.2.apk";

    private boolean mIsSimplifiedChinese;

    private TextView mAction;

    @Override
    protected void initArgs() {
        Resources resource = getResources();
        Configuration config = resource.getConfiguration();
        mIsSimplifiedChinese = config.locale == Locale.SIMPLIFIED_CHINESE;
    }

    @Override
    protected TitleBar initTitleBar() {
        TitleBar titleBar = super.initTitleBar().setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.exitBy2Click();
            }
        });
        mAction = (TextView) titleBar.addAction(new TitleBar.TextAction(mIsSimplifiedChinese ? "简体中文" : "系统默认") {
            @Override
            public void performAction(View view) {
                if (mIsSimplifiedChinese) {
                    changeLocale(Locale.getDefault());
                }else{
                    changeLocale(Locale.SIMPLIFIED_CHINESE);
                }
                mIsSimplifiedChinese = !mIsSimplifiedChinese;
                mAction.setText(mIsSimplifiedChinese ? "简体中文" : "系统默认");
            }
        });
        return titleBar;
    }

    private void changeLocale(Locale locale){
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        config.setLocale(locale);
        resources.updateConfiguration(config,null);
    }
    @Override
    protected List<String> initSimpleData(List<String> lists) {
        lists.add("默认App更新");
        lists.add("默认App更新 + 支持后台更新");
        lists.add("版本更新(自动模式)");
        lists.add("强制版本更新");
        lists.add("默认App更新 + 自定义提示弹窗主题");
        lists.add("默认App更新 + 自定义Api");
        lists.add("默认App更新 + 自定义Api + 自定义提示弹窗(系统）");
        lists.add("直接传入UpdateEntity进行更新");
        lists.add("使用apk下载功能");
        lists.add("使用apk安装功能");
        lists.add("版本更新提示框在FragmentActivity中使用UpdateDialogFragment, 在普通Activity中使用UpdateDialog");
        lists.add("使用XUpdateService版本更新服务");
        lists.add("获取文件的MD5值");
        return lists;
    }

    @Override
    protected void onItemClick(int position) {
        switch (position) {
            case 0:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl)
                        .update();
                break;
            case 1:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl)
                        .supportBackgroundUpdate(true)
                        .update();
                break;
            case 2:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl)
                        .isAutoMode(true)
                        .update();
                break;
            case 3:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl2)
                        .update();

                break;
            case 4:
                XUpdate.newBuild(getActivity())
                        .updateHttpService(new XHttpUpdateHttpService("https://gitee.com"))
                        .updateUrl("/xuexiangjys/XUpdate/raw/master/jsonapi/update_test.json")
                        //设置主题颜色
                        .promptThemeColor(ResUtils.getColor(R.color.update_theme_color))
                        //设置按钮的文字颜色
                        .promptButtonTextColor(Color.WHITE)
                        //设置顶部背景图片
                        .promptTopResId(R.mipmap.bg_update_top)
                        //设置版本更新提示器宽度占屏幕的比例，默认是-1，不做约束
                        .promptWidthRatio(0.7f)
                        .update();

                break;
            case 5:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl3)
                        .updateParser(new CustomUpdateParser())
                        .update();
                break;
            case 6:
                XUpdate.newBuild(getActivity())
                        .updateUrl(mUpdateUrl3)
                        .updateChecker(new DefaultUpdateChecker(){
                            @Override
                            public void onBeforeCheck() {
                                super.onBeforeCheck();
                                CProgressDialogUtils.showProgressDialog(getActivity(),"查询中...");
                            }

                            @Override
                            public void onAfterCheck() {
                                super.onAfterCheck();
                                CProgressDialogUtils.cancelProgressDialog(getActivity());
                            }

                            @Override
                            public void noNewVersion(Throwable throwable) {
                                super.noNewVersion(throwable);
                                ToastUtils.toast("无新版本可供下载");
                            }
                        })
                        .updateParser(new CustomUpdateParser())
                        .updatePrompter(new CustomUpdatePrompt())
                        .update();
                break;
            case 7:
                XUpdate.newBuild(getActivity())
                        .build()
                        .update(getUpdateEntityFromAssets());
                break;
            case 8:
                useAPKDownloadFunction();
                break;
            case 9:
                selectAPKFile();
                break;
            default:
                break;
        }

    }

    private UpdateEntity getUpdateEntityFromAssets(){
        return new DefaultUpdateParser().parseJson(ResourceUtils.readStringFromAssert("update_test.json"));
    }

    @Permission(PermissionConstants.STORAGE)
    private void useAPKDownloadFunction(){
        Log.e("extPath",PathUtils.getExtDownloadsPath());
        XUpdate.newBuild(getActivity())
                .apkCacheDir(PathUtils.getAppExtDownloadPath())
                .build()
                .download(mDownloadUrl, new OnFileDownloadListener() {
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(getContext(),"下载进度",false);
                    }

                    @Override
                    public void onProgress(float progress, long total) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    @Override
                    public boolean onCompleted(File file) {
                        HProgressDialogUtils.cancel();
                        ToastUtils.toast("APK下载完成，下载路径：" + file.getPath());
                        return false;
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        HProgressDialogUtils.cancel();
                    }
                });
    }

    @Permission(PermissionConstants.STORAGE)
    private void selectAPKFile(){
        startActivityForResult(IntentUtils.getDocumentPickerIntent(IntentUtils.DocumentType.ANY),1000);
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == 1000) {
                _XUpdate.startInstallApk(getContext(), FileUtils.getFileByPath(PathUtils.getFilePathByUri(getContext(),data.getData())));
            }
        }
    }
}

